<?php

use yii\helpers\Html;
//use yii\grid\GridView;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
use common\models\business\BusinessVariety;
use common\models\business\BusinessPig;
use common\models\business\BusinessException;
use yii\web\JsExpression;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\business\models\BusinessPigSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = '仔猪管理';
$this->params['breadcrumbs'][] = $this->title;
?>


<section class="wrapper site-min-height">
    <!-- page start-->
    <section class="panel">
        <header class="panel-heading">
              <?= Html::a('返回','javascript:history.back(-1)'); ?>  <?= Html::encode($this->title) ?>
        </header>
        <div class="panel-body">
            <div class="adv-table editable-table ">
 


<div class="business-pig-index">

    <p>
        <?= Html::a('添加仔猪', ['create'], ['class' => 'btn btn-success']) ?>

        <?php if(!\Yii::$app->request->get('id')){?>
        <?php $form = \yii\widgets\ActiveForm::begin(['action'=>'/business/pig/import','options' => ['enctype' => 'multipart/form-data']]); ?>
            <?= $form->field($immodel, 'excel')->fileInput() ?>

            <div class="form-group">
                <?= Html::submitButton('导入仔猪', ['class' => 'btn btn-primary']) ?>
                <?= Html::a('下载导入模板','/statics/导入模板.xlsx', ['class' => 'btn btn-success']) ?>

                <?= Html::label('批量预制仔猪编号','', ['class' => 'btn btn-success',
                    'data-toggle' => 'modal',
                    'data-target' => '#create-modal',]) ?>
            </div>
        <?php \yii\widgets\ActiveForm::end(); ?>

        <?php } ?>
    </p>



    <?php
        \yii\bootstrap\Modal::begin([
            'id' => 'create-modal',
            'header' => '<h4 class="modal-title">批量预制仔猪编号</h4>',
            'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">关闭</a>',
        ]);
        $requestUrl = \yii\helpers\Url::toRoute('createno');
        $js = "
            $.get('{$requestUrl}', {},
                function (data) {
                    console.log(data)
                    $('#create-modal .modal-body').html(data);
                } 
            );
        ";
        $this->registerJs($js);
        \yii\bootstrap\Modal::end();
    ?>



    <?php
        echo GridView::widget([
            'dataProvider'=>$dataProvider,
            'filterModel'=>$searchModel,
            'showPageSummary'=>true,
            'pjax'=>false,
            'striped'=>true,
            'hover'=>true,
            'panel'=>['type'=>'primary', 'heading'=>'仔猪管理'],
            'containerOptions'=>['style'=>'overflow: auto'], // only set when $responsive = false
            'headerRowOptions'=>['class'=>'kartik-sheet-style'],
            'filterRowOptions'=>['class'=>'kartik-sheet-style'],
            'columns'=>[

                [
                    'class'=>'kartik\grid\ExpandRowColumn',
                    'width'=>'50px',
                    'value'=>function ($model, $key, $index, $column) {
                        return GridView::ROW_COLLAPSED;
                    },
                    'detail'=>function ($model, $key, $index, $column) {
                        return Yii::$app->controller->renderPartial('_inspection', ['model'=>$model]);
                    },
                    'headerOptions'=>['class'=>'kartik-sheet-style'],
                    'expandOneOnly'=>true
                ],
                [
                    'attribute'=>'no',
                    'pageSummaryOptions'=>['class'=>'text-right text-warning'],
                    'width'=>'90px',
                ],
                [
                    'attribute'=>'batch',
                    'width'=>'40px',
                ],
                [
                    'attribute'=>'headpersonid',
                    'format' => 'raw',
                    'value' => function($model){
                        return $model->person?Html::a($model->person->name,\yii\helpers\Url::to(['/business/person/view','id'=>$model->person->id])):'(未设置)';
                    },
                    'pageSummaryOptions'=>['class'=>'text-right text-warning'],
                    'width'=>'100px',
                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=>ArrayHelper::map(\common\models\business\BusinessPerson::find()->asArray()->all(),'id','name'),
                    'filterWidgetOptions'=>[
                        'pluginOptions'=>['allowClear'=>true],
                    ],
                    'filterInputOptions'=>['placeholder'=>'业务人'],
//                    'group'=>true,  // enable grouping
                ],
                [
                    'attribute'=>'livery',
                    'format' => 'raw',
                    'value' => function($model){
                        return $model->liveryperson?Html::a($model->liveryperson->name,\yii\helpers\Url::to(['/business/farmers/view','id'=>$model->liveryperson->id])):'(未设置)';
                    },
                    'pageSummaryOptions'=>['class'=>'text-right text-warning'],
                    'width'=>'60px',
                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=>ArrayHelper::map(\common\models\business\BusinessFarmers::find()->asArray()->all(),'id','name'),
                    'filterWidgetOptions'=>[
                        'pluginOptions'=>['allowClear'=>true],
                    ],
                    'filterInputOptions'=>['placeholder'=>'代养农户','style'=>'width:50px'],
//                    'group'=>true,  // enable grouping
                ],
                [
                    'label' => '种类',
                    'attribute'=>'varietyid',
                    'format' => 'raw',
                    'value' => function($model){
                        return $model->variety?Html::a($model->variety->title,\yii\helpers\Url::to(['/business/variety/view','id'=> $model->variety->id])):'(未设置)';
                    },
                    'width'=>'100px',
                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=>ArrayHelper::map(BusinessVariety::find()->asArray()->all(),'id','title'),
                    'filterWidgetOptions'=>[
                        'pluginOptions'=>['allowClear'=>true],
                    ],
                    'filterInputOptions'=>['placeholder'=>'选择种类'],
//                    'group'=>true,  // enable grouping
                ],
                [
                    'attribute'=>'canlivery',
                    'width'=>'80px',
                    'value'=>function ($model, $key, $index, $widget) {
                        return BusinessPig::$canlivery[$model->canlivery];
                    },
                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=> BusinessPig::$canlivery,
                    'filterWidgetOptions'=>[
                        'pluginOptions'=>['allowClear'=>true],
                    ],
                    'filterInputOptions'=>['placeholder'=>'是否可以领养']
                ],
                [
                    'attribute'=>'cost',
                    'width'=>'50px',
                    'hAlign'=>'right',
                    'format'=>['decimal', 2],
                    'pageSummary'=>true,
                ],
                [
                    'attribute'=>'price',
                    'width'=>'50px',
                    'hAlign'=>'right',
                    'format'=>['decimal', 0],
                    'pageSummary'=>true,
                ],
                [
                    'attribute'=>'planout',
                    'value' => function($model){
                        return date('Y-m-d',$model->planout);
                    },
                    'width'=>'200px',
                    'hAlign'=>'right',
                    'filterType' => GridView::FILTER_DATE_RANGE,
                    'filterWidgetOptions' =>([
                        'attribute'=>'planout',
                        'presetDropdown'=>false,
                        'convertFormat'=>true,
                            'pluginOptions'=>[
                                'separator'=>'至',
                                'format'=>'Y-m-d',
                                'opens'=>'left',
                            ],
                        ])
                ],
                [
                    'attribute'=>'status',
                    'width'=>'60px',
                    'format' => 'raw',
                    'value'=>function ($model, $key, $index, $widget) {

                        $outdays = \common\models\sys\SysSetting::getValue('waitout');

                        if($model->status==BusinessPig::STATUS_EXCEPTION){
                            $exception = BusinessException::find()->select('reason')->where('pigid=:id',[':id'=>$model->id])->asArray()->one();
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-danger','data-id'=>$model->id,'data-toggle'=>'tooltip','data-placement'=>'top','title'=>$exception['reason']]);
                        }else if($model->status==BusinessPig::STATUS_KILLED){
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-success']);
                        }else if($model->status==BusinessPig::STATUS_WAITKILL){
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-primary']);
                        }else if($model->planout-time() <= $outdays*3600*24 && !empty($model->planout)){
                            return Html::label('预出栏', '', ['class' => 'btn btn-xs','style'=>'background:orange']);
                        }else if($model->status==BusinessPig::STATUS_BRFOREIN) {
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-default']);
                        }else if($model->status==BusinessPig::STATUS_AFTERIN){
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-primary']);
                        }else if($model->status==BusinessPig::STATUS_WAITOUT){
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-info']);
                        }

                        return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-default']);
                    },
                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=> BusinessPig::$statues,
                    'filterWidgetOptions'=>[
                        'pluginOptions'=>['allowClear'=>true],
                    ],
                    'filterInputOptions'=>['placeholder'=>'选择状态']
                ],
                [
                    'attribute' => 'isinspection',
                    'label' => '是否巡检',
                    'format' => 'raw',
                    'value'=>function($model){
                        if($model->status != BusinessPig::STATUS_AFTERIN){
                            return Html::label(BusinessPig::$statues[$model->status], '', ['class' => 'btn btn-xs btn-default']);
                        }
                        if($model->isinspection){
                            return Html::label( '已经巡检','',['class' => 'btn btn-xs btn-success']);
                        }else{
                            return Html::label('待巡检', '', ['class' => 'btn btn-xs btn-danger']);
                        }
                    },

                    'filterType'=>GridView::FILTER_SELECT2,
                    'filter'=> [1=>'待巡检',2=>'已巡检'],
                    'filterWidgetOptions'=>[
                        'pluginOptions'=>['allowClear'=>true],
                    ],
                    'filterInputOptions'=>['placeholder'=>'巡检状态'],
                    'width'=>'100px',
                    'hAlign'=>'right',
                ],
                [
//                    'class' => '\kartik\grid\ActionColumn',
//                    'deleteOptions' => ['label' => '<i class="glyphicon glyphicon-remove"></i>'],
//                    'template' => '{view},{update},{delete}',
//                    'button' => [
//                        'view' => function($model){
//                            if($model->status == BusinessPig::STATUS_DIEED){
//                                return '';
//                            }
//                        }
//                    ]
                ],
                [
                    'class' => '\kartik\grid\ActionColumn',
                    'deleteOptions' => ['label' => '<i class="glyphicon glyphicon-remove"></i>'],
                    'template' => '{view}{update}{delete}{qxling}',
                    'buttons' => [
                        'qxling' => function ($url, $model) {
                            if($model->lingperson){
                                return Html::a('取消认养人',\yii\helpers\Url::to(['qx-ling','id'=>$model->id]),[
                                    'title' => '取消认养人','class'=>'view','data-id'=>$model->id,
                                ]);
                            }

                        },
                    ],
                ],
                [
                    'class' => '\kartik\grid\CheckboxColumn'
                ]
            ],
            'toolbar'=> [
                [
                    'content' => Html::button('<i class="glyphicon glyphicon-delete">批量设置仔猪成本售价</i>', ['type'=>'button', 'title'=>'批量设置仔猪成本售价', 'class'=>'btn btn-success', 'id'=>'setcost','data-toggle'=>"modal",'data-target'=>"#setcost-model"])
                ],
                [
                    'content' => Html::button('<i class="glyphicon glyphicon-delete">批量设置仔猪信息</i>', ['type'=>'button', 'title'=>'批量设置出栏时间', 'class'=>'btn btn-success', 'id'=>'settime'])
                ],
                [
                    'content' => Html::button('<i class="glyphicon glyphicon-delete">删除选中仔猪</i>', ['type'=>'button', 'title'=>'删除选中仔猪', 'class'=>'btn btn-success', 'id'=>'delpig'])
                ],
                [
                    'content' => Html::button('<i class="glyphicon glyphicon-download"></i>', ['type'=>'button', 'title'=>'下载选择仔猪的二维码', 'class'=>'btn btn-success', 'id'=>'addpig'])
                ],
                '{export}',
                '{toggleData}',
            ],
            'bordered'=>true,
            'condensed'=>true,
        ]);
    ?>



    <!--设置出栏时间-->
    <div id="settime-modal" class="fade modal in" role="dialog">
        <div class="modal-dialog ">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title">批量设置仔猪信息</h4>
                </div>
                <div class="modal-body">
                    <form method="post" action="/business/pig/settime">
                        <div class="form-group">
                            <label for="intime">入栏日期</label>
                            <input type="date" name="intime" class="form-control" id="intime" placeholder="入栏日期">
                        </div>


                        <div class="form-group">
                            <label for="tooutnum">距入栏多少天出栏</label>
                            <input type="number" name="tooutnum" class="form-control" id="tooutnum" placeholder="距入栏多少天出栏">
                        </div>

                        <div class="form-group">
                            <label for="tooutnum">批次</label>
                            <input type="text" name="batch" class="form-control" id="batch" placeholder="批次">
                        </div>

                        <div class="form-group">
                            <label for="tooutnum">领养价格</label>
                            <input type="text" name="price" class="form-control" id="batch" placeholder="价格">
                        </div>

                        <div class="form-group">
                            <label for="tooutnum">是否领养首页展示</label>
                            <select name="isindex" class="form-control"  id="">
                                <?php foreach(BusinessPig::$isindex as $key => $row){ ?>
                                    <option value="<?=$key?>"><?=$row ?></option>
                                <?php } ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="tooutnum">猪种</label>
                            <select name="varietyid" class="form-control"  id="">
                                <?php foreach($varietys as $key => $row){ ?>
                                    <option value="<?=$key?>"><?=$row ?></option>
                                <?php } ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="tooutnum">是否可以领养</label>
                            <select name="canlivery" class="form-control"  id="">
                                <?php foreach(BusinessPig::$canlivery as $key => $row){ ?>
                                    <option value="<?=$key?>"><?=$row ?></option>
                                <?php } ?>
                            </select>
                        </div>


                        <?php
                        echo Html::label('档案号');
                        echo \kartik\select2\Select2::widget([
                            'name' => 'fileid',
                            'options' => ['placeholder' => '请输入仔猪所属的档案编号 ...'],
                            'initValueText'=>'',
                            'pluginOptions' => [
                                'allowClear' => true,
                                'minimumInputLength' => 1,//重要
                                'language' => [
                                    'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"),
                                ],
                                'ajax' => [
                                    'url' => '/business/search/search-file',
                                    'dataType' => 'json',
                                    'data' => new JsExpression('function(params) { return {q:params.term}; }'),
                                    'cache' => true
                                ],
                                'width' => '400px',
                                'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                                'templateResult' => new JsExpression('function(res) { return res.text; }'),
                                'templateSelection' => new JsExpression('function (res) { return res.text; }'),
                            ],
                        ]);
                        ?>

                        <?php
                            echo Html::label('巡检员');
                            echo \kartik\select2\Select2::widget([
                                'name' => 'headpersonid',
                                'options' => ['placeholder' => '请输入巡检仔猪的业务员姓名 ...'],
                                'initValueText'=>'',
                                'pluginOptions' => [
                                    'allowClear' => true,
                                    'minimumInputLength' => 1,//重要
                                    'language' => [
                                        'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"),
                                    ],
                                    'ajax' => [
                                        'url' => '/business/search/search-person',
                                        'dataType' => 'json',
                                        'data' => new JsExpression('function(params) { return {q:params.term}; }'),
                                        'cache' => true
                                    ],
                                    'width' => '400px',
                                    'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                                    'templateResult' => new JsExpression('function(res) { return res.text; }'),
                                    'templateSelection' => new JsExpression('function (res) { return res.text; }'),
                                ],
                            ]);
                        ?>

                        <?php
                        echo Html::label('农户');
                        echo \kartik\select2\Select2::widget([
                            'name' => 'livery',
                            'options' => ['placeholder' => '请输入代养仔猪的农户姓名 ...'],
                            'initValueText'=>'',
                            'pluginOptions' => [
                                'allowClear' => true,
                                'minimumInputLength' => 1,//重要
                                'language' => [
                                    'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"),
                                ],
                                'ajax' => [
                                    'url' => '/business/search/search-farmer',
                                    'dataType' => 'json',
                                    'data' => new JsExpression('function(params) { return {q:params.term}; }'),
                                    'cache' => true
                                ],
                                'width' => '400px',
                                'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                                'templateResult' => new JsExpression('function(res) { return res.text; }'),
                                'templateSelection' => new JsExpression('function (res) { return res.text; }'),
                            ],
                        ]);
                        ?>
                        <div class="form-group">
                            <label for="tooutnum">状态</label>
                            <select name="status" class="form-control"  id="">
                                <option value=""></option>
                                <?php foreach(BusinessPig::$statues as $key => $row){ ?>
                                    <option value="<?=$key?>"><?=$row ?></option>
                                <?php } ?>
                            </select>
                        </div>


                        <input type="hidden" class="form-control" id="_csrf" name="_csrf" value="ZWN0b3pRU1hUECYEG3wSNhIrLg4sKWEbPSU/HSxjGhAdMzwZHWY7FA==">
                        <input type="hidden" id="ids" name="ids" value="">
                        <button type="submit" class="btn btn-success">确认</button>
                    </form>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-primary" data-dismiss="modal">关闭</a>
                </div>
            </div>
        </div>
    </div>



    <!-- 批量设置仔猪成本价格弹窗 -->
    <div class="modal fade" id="setcost-model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">设置仔猪成及售价</h4>
                </div>
                <div class="modal-body">

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>


</div>
</div>
</div>
</section>
</section>
<script>
    <?php $this->beginBlock('js_end') ?>

        function contains(arr, obj) {
            var i = arr.length;
            while (i--) {
                if (arr[i] === obj) {
                    return true;
                }
            }
            return false;
        }

        $(function () {
            //初始化提示
            $('[data-toggle="tooltip"]').tooltip();

            var idarr = <?= $idarr ?>;
            console.log(idarr);
            if(idarr.length != 0){
                $('input[name="selection[]"]').each(function(i){
                    console.log(($(this).val()).toString());
                    if(contains(idarr,$(this).val())){
                        $(this).attr('checked',true);
                    }
                })
            }
        })


        $('#addpig').click(function () {
            var keys = jqchk();
            window.location.href = '/business/pig/download-qr?ids='+keys;
        });

        $('#delpig').click(function () {
            var keys = jqchk();
            if(confirm('确定要删除选中的仔猪')){
                $.post('/business/pig/deletepigs',{'ids':keys},function(res){
                    console.log(res);
                    alert(res.msg);
                    if(res.status == 0)
                        window.location.href='/business/pig/index';
                },'json');
            }
        });


        //批量设置时间
        $('#settime').click(function () {
            var keys = jqchk();
            if(keys.length == 0){
                alert('请选择要设置的仔猪');
                return false;
            }
            $('#settime-modal').modal();
            $('#ids').val(keys.join(','));

        })


        //批量设置成本售价
        $('#setcost').click(function () {
            var keys = jqchk();
            if(keys.length == 0){
                alert('请选择要设置的仔猪');
                return false;
            }
            $.get('/business/pig/set-pigcost',{'ids':keys},function(res){
                $('#setcost-model .modal-body').html(res);
                $('#setcost-modal').modal(res);
//                $('#ids').val(keys.join(','));
            });


        })

        function jqchk() { //jquery获取复选框值=
            var chk_value = [];
            $('input[name="selection[]"]:checked').each(function () {
                chk_value.push($(this).val());
            });
            return chk_value;
        }



    <?php $this->endBlock(); ?>
    <?php $this->registerJs($this->blocks['js_end'],\yii\web\View::POS_END);//将编写的js代码注册到页面底部 ?>
</script>




